package org.jetnuke.modules.content;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.PagesDAO;
import org.jetnuke.entities.Pages;
import org.jetnuke.entities.PagesCategories;

public class ShowPage implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ShowPage.class);

	int pid;
	int npage = 0;

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		String template = "page.vm";
		PagesDAO pm = DataAccessDriver.getInst().newPagesDAO();
		Pages pg = DataAccessDriver.getInst().newPagesDAO().retrieveByPK(pid);// pagesPeer.retrieveByPK(pid);

		if (pg == null || pg.getACTIVE() == 0 /* && isNotAdministrator */) {
			template = "pageNotFound.vm";
		} else {
			PagesCategories cat = DataAccessDriver.getInst().newPagesCatDAO()
					.retrieveByPK(pg.getCID());

			vc.put("cat", cat);
			vc.put("page", pg);
			String splitPages[] = pg.getTEXT().split("<!--pagebreak-->");
			int pageCount = splitPages.length;
			if (npage < 1)
				npage = 1;
			if (npage > pageCount)
				npage = pageCount;

			if (npage == 1) {
				pg.setCOUNTER(pg.getCOUNTER() + 1);
				pm.update(pg);
				// pg.save();
			}
			vc.put("pageCount", new Integer(pageCount));
			vc.put("npage", new Integer(npage));
			vc.put("text", splitPages[npage - 1]);

		}
		ActionForward returnActionForward = new ActionForward(info, template);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

	public void setPid(int pid) {
		this.pid = pid;
	}

	/**
	 * @param page
	 *            The page to set.
	 */
	public void setNpage(int npage) {
		this.npage = npage;
	}
}
